package com.github.shiqiyue.blog.markdown.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.github.shiqiyue.blog.markdown.entity.User;
import com.github.shiqiyue.blog.markdown.exception.ApplicationRuntimeException;
import com.github.shiqiyue.blog.markdown.repository.UserRepository;

/***
 * 会员服务
 * 
 * @author wwy
 *
 */
@CacheConfig(cacheNames = "cache.user")
@Service
public class UserService implements UserDetailsService {
	
	@Autowired
	private UserRepository repository;
	
	@Autowired
	@Qualifier("userPasswordEncoder")
	private PasswordEncoder passwordEncoder;
	
	/***
	 * 用户注册
	 * 
	 * @param user
	 */
	public void register(User user) {
		// 判断用户名是否存在
		if (countByUsername(user.getUsername()) > 0) {
			throw new ApplicationRuntimeException("用户名已存在");
		}
		// 判断邮箱是否存在
		if (countByEmail(user.getEmail()) > 0) {
			throw new ApplicationRuntimeException("邮箱已存在");
		}
		// 密码加密
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		save(user);
	}
	
	@CacheEvict(allEntries = true)
	public User save(User user) {
		return repository.save(user);
	}
	
	@CacheEvict(allEntries = true)
	public void delete(List<User> userList) {
		repository.delete(userList);
	}
	
	@Cacheable
	public User findByUsername(String username) {
		return repository.findByUsername(username);
	}
	
	@Cacheable
	public Long countByUsername(String username) {
		return repository.countByUsername(username);
	}
	
	@Cacheable
	public Long countByEmail(String email) {
		return repository.countByEmail(email);
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		return findByUsername(username);
	}
	
}
